<template>
  <view class="container">
    <view class="search-bar">
        <input
            v-model="query"
            @input="onInput"
            class="search-input"
            placeholder="搜索"
        />
        <view class="cancel-button" @click="onCancel">取消</view>
    </view>
    <view v-if="filteredList.length" class="suggestions">
        <scroll-view
            class="suggestions"
            scroll-y
            style="height: 80vh;"
            @scrolltolower="loadMore"
            >
            <view
                v-for="item in filteredList"
                :key="item.id"
                class="suggestion-item"
                @click="onItemFn(item)"
            >
              {{ item.brandName }}/{{ item.seriesName ? item.seriesName + '/' : '' }}{{ item.productName }}
            </view>

            <view class="loading-text" v-if="loadingMore">加载中...</view>
            <view class="loading-text" v-if="noMore">没有更多了</view>
        </scroll-view>
    </view>
    <view v-else class="no-results">
      没有找到相关结果
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { request } from '../utils/request'

const query = ref('')
const filteredList = ref([])
const current = ref(1)
const size = 10
const loadingMore = ref(false)
const noMore = ref(false)
// const dataList = [
//   'Gavinfly D42CO',
//   '太阳镜 Tiffany & Co./蒂芙尼',
//   '耳钉 Tiffany & Co./蒂芙尼',
//   '项链 Tiffany & Co./蒂芙尼',
//   '戒指指环 Tiffany & Co./蒂芙尼'
// ]

// const filteredList = computed(() =>
//   query.value
//     ? dataList.filter(item =>
//         item.toLowerCase().includes(query.value.toLowerCase())
//       )
//     : []
// )
function debounce(fn, delay = 300) {
  let timer
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}
const fetchSuggestions = async (isLoadMore = false) => {
    if (!query.value) {
        filteredList.value = []
        return
    }
    loadingMore.value = true
    const res = await request({
        url: '/product/search',
        method: 'get',
        header: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: {
            name: query.value,
            current: current.value,
            size
        }
    })
    const records = res.data.records || []
    if (isLoadMore) {
        filteredList.value = [...filteredList.value, ...records]
    } else {
        filteredList.value = records
    }
    if (records.length < size) {
        noMore.value = true
    }
    loadingMore.value = false
}
const debouncedFetch = debounce(() => {
    current.value = 1
    noMore.value = false
    fetchSuggestions()
}, 500)
const onInput = async(e) => {
    query.value = e.detail.value
    debouncedFetch()
}

const onItemFn = (item) => {
    const name = `${item.brandName}/${item.productName}`
    uni.navigateTo({
        url: `/pages/index/form2?name=${encodeURIComponent(name)}`
    })
}
const loadMore = () => {
  if (loadingMore.value || noMore.value) return
  current.value += 1
  fetchSuggestions(true)
}

const onCancel = () => {
    query.value = '';
    uni.navigateBack();
}
</script>

<style scoped>
.container {
  padding: 16px;
}
.search-bar {
  display: flex;
  align-items: center;
}
.search-input {
  flex: 1;
  height: 36px;
  padding: 0 12px;
  border: 4rpx solid #000;
  border-radius: 36rpx;
  font-size: 14px;
  margin-right: 20rpx;
}

.suggestions {
  margin-top: 12px;
}
.suggestion-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  color: #333;
}
.no-results {
  text-align: center;
  color: #999;
  margin-top: 20px;
}
.loading-text {
  text-align: center;
  padding: 10px 0;
  color: #999;
}
</style>
